package com.example.demo.aop;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LogAspect {

    //切入点
    @Pointcut(value = "execution (* com.example.demo.controller.*.*(..))")
    public void pointCut1() {
    }
    @Pointcut(value = "execution (* com.example.demo.common.*.*(..))")
    public void pointCut2() {
    }

    @Around(value = "pointCut1()")
    public Object  doAround1(ProceedingJoinPoint point) throws Throwable{
        return printInfo(point);

    }
    @Around(value = "pointCut2()")
    public Object doAround2(ProceedingJoinPoint point) throws Throwable{
        return printInfo(point);
    }

    private Object printInfo(ProceedingJoinPoint point) throws Throwable{
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();

            String param = new ObjectMapper().writeValueAsString(request.getParameterMap());
            log.info("==> Request uri: {}, ip: {}, param: {}", request.getRequestURI(), request.getRemoteAddr(), param);
        } else {
            log.info("attributes is null, request not bound");
        }
       return point.proceed();
    }

}
